package com.sy.controller;

import com.sy.dto.UserSession;
import com.sy.exception.WebException;
import com.sy.utils.CommonUtils;
import com.sy.utils.RandomUtils;
import com.sy.utils.RedisOperations;
import com.sy.vo.LoginVo;
import org.apache.commons.lang.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Objects;

import static com.sy.constant.BusinessConstant.*;

@RestController
public class LoginController extends BaseController{
    @Autowired(required = false)
    private RedisOperations redisOperations;
    //登录
    @RequestMapping(value = "users/login",method = RequestMethod.POST)
    public UserSession login(String account, String password, String identity){

        LoginVo loginVo = new LoginVo();
        loginVo.setAccount(account);
        loginVo.setPassword(password);
        loginVo.setIdentity(identity);

        UserSession userSession = loginService.login(loginVo);

        HttpSession httpSession = req.getSession();
        httpSession.setAttribute("session",userSession);
        Object session = httpSession.getAttribute("session");
        System.out.println("登录时的"+session);
        return userSession;
    }

    //验证登录
    @RequestMapping(value = "users/loginUser",method = RequestMethod.GET)
    public UserSession getLoginUser() {

        UserSession userSession = (UserSession) req.getSession().getAttribute("session");
        if(Objects.isNull(userSession) || Objects.equals("",userSession)){
            throw new WebException("用户尚未登录");
        }else {
            return userSession;
        }
    }

    //登出
    @RequestMapping(value = "users/loginOut",method = RequestMethod.POST)
    public boolean loginOut(){
        UserSession userSession = (UserSession) req.getSession().getAttribute("session");
        if(Objects.nonNull(userSession)) {
            req.getSession().setAttribute("session", null);
        }
        return true;
    }
}
